package com.michael.study.jetpack.module.login

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.michael.study.jetpack.bean.UserInfo
import com.michael.study.jetpack.network.Api
import com.michael.study.jetpack.network.ApiResult
import com.michael.study.jetpack.network.body.LoginBody
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.await

/**
 * Description:
 *
 * Created by liuguoquan on 2020/3/19 19:46.
 */
class LoginViewModel : ViewModel() {

    var user: MutableLiveData<ApiResult<UserInfo>> = MutableLiveData()

    fun login(condition: LoginCondition) {
        var body = LoginBody()
        body.username = condition.userName;
        body.password = condition.password;
        var call = Api.getLoginApi().login(body)
        call.enqueue(object : Callback<ApiResult<UserInfo>> {
            override fun onResponse(
                call: Call<ApiResult<UserInfo>>,
                response: Response<ApiResult<UserInfo>>
            ) {
                Log.d("lgq", response.body()?.data.toString())
                user.value = response.body()
            }

            override fun onFailure(call: Call<ApiResult<UserInfo>>, t: Throwable) {

            }
        })
    }

    fun loginCoroutineScope(condition: LoginCondition) {
        CoroutineScope(Dispatchers.Main).launch {
            var ret = suspendingRequestUser(condition)
            user.value = ret

        }
    }

    private suspend fun suspendingRequestUser(condition: LoginCondition) =
        withContext(Dispatchers.IO) {
            try {
                var body = LoginBody()
                body.username = condition.userName
                body.password = condition.password
                var result = Api.getLoginApi().login(body).await()
                return@withContext result
            } catch (e :Throwable) {
                var result = ApiResult<UserInfo>()
                result.code = -1
                result.msg = e.message
                return@withContext  result
            }

        }
}